package nl.infodation.emr.pricingservice.ui;

import java.util.Locale;

import nl.infodation.emr.pricingservice.data.AdvantageItem;
import nl.infodation.emr.pricingservice.data.ConditionItem;
import nl.infodation.emr.pricingservice.entity.DomainRule;
import nl.infodation.emr.pricingservice.ui.component.AbstractBasePanel;
import nl.infodation.emr.pricingservice.ui.page.PricingServiceApplication;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.DateTimeUtil;
import nl.infodation.emr.utility.StringUtil;

import com.github.peholmst.i18n4vaadin.I18N;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;

public class MainView extends AbstractBasePanel implements ClickListener {
	private static final long serialVersionUID = 1L;

	private Button btnConditionSelection;
	private Button btnAdvantageDefinition;
	private Button btnOverview;
	private Button btnConfiguration;
	private Button btnUsers;
	private Button btnLogout = new NativeButton();

	private Label lblVersion;

	private UsersManagementView usersManagementView;
	private ConditionView conditionView;
	private AdvantageView advantageView;
	private ActiveDomainRuleListView activeDomainRuleListView;
	private ConfigurationView configurationView;
	private CustomLayout mainViewLayout;
	private String username;

	public String getUsername() {
		return username;
	}

	public MainView(String username) {
		super();
		this.username = username;
		initialize();
		initViews();
		showPromotionListView(Boolean.TRUE);
		addListener();
		setBinding();
		makePrivileges();
		mainViewLayout.setStyleName("main_view");
	}

	public String getCountryCodeFromConditionView() {
		return ((ConditionView) getConditionSelectionView()).getCountryCode();
	}

	public void setCountryCodeFromConditionView(String value) {
		((ConditionView) getConditionSelectionView()).setCountryCode(value);
	}

	public String getLanguageCodeFromConditionView() {
		return ((ConditionView) getConditionSelectionView()).getLanguageCode();
	}
	
	public String getBusLineConditionView() {
		return ((ConditionView) getConditionSelectionView()).getBussinessLine();
	}

	public void setVisibleOrderLineDiscountFromAdvantageView(Boolean value) {
		((AdvantageView)getAdvantageDefinitionView()).setVisibleOrderLineDiscountPerc(value);
	}
	
	public void setOrderLineDiscountStateFromAdvantageView(String priceType) {
		((AdvantageView)getAdvantageDefinitionView()).setOrderLineDiscountState(priceType);
	}
	
	public String getBusinessChosen() {
		return ((ConfigurationView) getConfigurationView()).getBusinessChosen();
	}
	
	public String getPriceType() {
		return ((ConditionView) getConditionSelectionView()).getPriceType();
	}

	private void makePrivileges() {
		// Only super admins can do users function
		if (!SessionData.isSuperAdmin()) {
			mainViewLayout.removeComponent(btnConfiguration);
			if (!SessionData.isNormalAdmin()) {
				mainViewLayout.removeComponent(btnUsers);
			}
		}
	}

	private void initNaviButton() {
		btnConditionSelection = new NativeButton(SessionData.getI18N()
				.getMessage(Constants.CONDITION_SELECTION_BUTTON));

		btnAdvantageDefinition = new NativeButton(SessionData.getI18N()
				.getMessage(Constants.ADVANTAGE_DEFINITION_BUTTON));

		btnOverview = new NativeButton(SessionData.getI18N().getMessage(
				Constants.ACTIVE_PROMOTIONS_BUTTON));

		btnUsers = new NativeButton(SessionData.getI18N().getMessage(
				Constants.USERS_BUTON));

		btnConfiguration = new NativeButton(SessionData.getI18N().getMessage(
				Constants.CONFIGURATION_BUTON));
	}

	private void initViews() {
		conditionView = new ConditionView(this);
		advantageView = new AdvantageView(this);
		activeDomainRuleListView = new ActiveDomainRuleListView(this);
	}

	public Component getCurrentView() {
		// return horizontalSplit.getFirstComponent();
		return mainViewLayout.getComponent("content_containner");
	}

	private void setBinding() {
		ObjectProperty<String> busProp = new ObjectProperty<String>("",
				String.class);
		ObjectProperty<String> ruleProp = new ObjectProperty<String>("",
				String.class);
		String envString = "";
		if (SessionData.getEnvironment() == Constants.PRE_PROD_ENVIROMENT) {
			envString = SessionData.getI18N().getMessage(
					Constants.PRE_PROD_ENVIROMENT_MESSAGE);
		} else if (SessionData.getEnvironment() == Constants.UAT_ENVIROMENT) {
			envString = SessionData.getI18N().getMessage(
					Constants.UAT_ENVIROMENT_MESSAGE);
		}
		ObjectProperty<String> envName = new ObjectProperty<String>(envString,
				String.class);

		((ConditionView) getConditionSelectionView()).setBinding(busProp,
				ruleProp, envName);
		((AdvantageView) getAdvantageDefinitionView()).setBinding(busProp,
				ruleProp, envName);
		((UsersManagementView) getUserManagementView()).setBinding(envName);
		((ActiveDomainRuleListView) getActivePromotionListView())
				.setBinding(envName);
	}

	public void setDetailView(DomainRule domainRule, Boolean isUpdateRequest) {
		ConditionItem condItem = domainRule.getConditionItem();
		setConditionViewContent(condItem, isUpdateRequest);

		AdvantageItem advItem = domainRule.getAdvantageItem();
		setAdvantageViewContent(advItem);
	}

	public boolean isValidated() {
		return advantageView.validate() && conditionView.validate();
	}

	public DomainRule getCurrentDomainRule() {
		ConditionItem condItem = conditionView.getContentValues();
		AdvantageItem advItem = advantageView.getContentValues();

		DomainRule domainRule = new DomainRule();
		domainRule.setDomainRule(condItem, advItem);

		// update domain rule in overview page if any
		if (activeDomainRuleListView.getCurDomainRule() != null
				&& ((DomainRule) (activeDomainRuleListView.getCurDomainRule()))
						.getDomainRuleId().equals(condItem.getDomainRuleId())) {

			((DomainRule) (activeDomainRuleListView.getCurDomainRule()))
					.setDomainRule(condItem, advItem);
		}
		return domainRule;

	}

	private void setConditionViewContent(ConditionItem item,
			boolean isUpdateRequest) {
		conditionView.setContentValues(item, isUpdateRequest);
	}

	private void setAdvantageViewContent(AdvantageItem item) {
		advantageView.setContentValues(item);
	}

	private void setConditionViewButtonEnabled(boolean enabled) {
		btnConditionSelection.setEnabled(enabled);
	}

	private void setAdvantageViewButtonEnabled(boolean enabled) {
		btnAdvantageDefinition.setEnabled(enabled);
	}

	private void setPromotionListViewButtonEnabled(boolean enabled) {
		btnOverview.setEnabled(enabled);
	}

	private void addListener() {
		btnConditionSelection.addListener(this);
		btnAdvantageDefinition.addListener(this);
		btnOverview.addListener(this);
		btnUsers.addListener(this);
		btnConfiguration.addListener(this);
		btnLogout.addListener(this);
	}

	public void showDetail() {
		setPromotionListViewButtonEnabled(false);
		setAdvantageViewButtonEnabled(true);
		setConditionViewButtonEnabled(true);
		showConditionSelectionView();
	}

	public void showPromotionListView(boolean reset) {
		showPromotionListView(reset, Boolean.FALSE);
	}
	
	public void showPromotionListView(boolean reset, boolean isResearch) {
		setPromotionListViewButtonEnabled(true);
		setAdvantageViewButtonEnabled(false);
		setConditionViewButtonEnabled(false);
		showActivePromotionListView(reset, isResearch);
	}

	@Override
	public void reload() {

	}

	@Override
	public void initLayout() {
		mainViewLayout = new CustomLayout("MainView");
		// // New layout
		createTopControl();
		mainViewLayout.addComponent(lblVersion, "Version");
		mainViewLayout.addComponent(btnLogout, "logout");
		mainViewLayout.addComponent(btnOverview, "ActivePromotions");
		mainViewLayout.addComponent(btnAdvantageDefinition,
				"Add_ActivePromotions2");
		mainViewLayout.addComponent(btnConditionSelection,
				"Add_ActivePromotions");
		mainViewLayout.addComponent(btnUsers, "User");
		mainViewLayout.addComponent(btnConfiguration, "Configuration");

		this.setContent(mainViewLayout);
	}

	private void createTopControl() {
		initNaviButton();
		lblVersion = new Label();

		if (StringUtil.isCodeVersion(SessionData.getVersion())) {
			lblVersion.setWidth(50, Label.UNITS_PIXELS);
			lblVersion.setValue(Constants.VERSION_CODE);
			lblVersion.setStyleName("viewmain-versioncorrect");
		} else {
			lblVersion.setStyleName("viewmain-versionnotcorrect");
			lblVersion.setValue(SessionData.getI18N().getMessage(
					Constants.VERSION_DATABASE)); 
		}

		btnLogout.setStyleName("logout_button");
		btnOverview.setStyleName("top_button_current");
		btnAdvantageDefinition.setStyleName("top_button");
		btnConditionSelection.setStyleName("top_button");
		btnUsers.setStyleName("top_button");
		btnConfiguration.setStyleName("top_button");
	}

	public void buttonClick(ClickEvent event) {

		final Button source = event.getButton();

		if (source == btnConditionSelection) {
			LOG.info(DateTimeUtil.getNow() + "Click to show condition page");
			showConditionSelectionView();

		} else if (source == btnAdvantageDefinition) {
			LOG.info(DateTimeUtil.getNow() + "Click to show advantage page");
			showAdvantageDefinitionView();

		} else if (source == btnOverview) {
			LOG.info(DateTimeUtil.getNow() + "Click to show overview page");
			DomainRuleList.getActiveList().clear();
			showActivePromotionListView(Boolean.TRUE);

		} else if (source == btnUsers) {
			LOG.info(DateTimeUtil.getNow()
					+ "Click to show user management page");
			showUserManagementView();

		} else if (source == btnConfiguration) {
			LOG.info(DateTimeUtil.getNow() + "Click to show configuration page");
			showConfigurationView();

		} else if (source == btnLogout) {
			LOG.info(DateTimeUtil.getNow() + "User logout");
			showLoginView();
		}
	}

	public void showConfigurationView() {

		btnAdvantageDefinition.setStyleName("top_button");
		btnConditionSelection.setStyleName("top_button");
		btnConfiguration.setStyleName("top_button_current");
		btnOverview.setStyleName("top_button");
		btnUsers.setStyleName("top_button");

		setMainComponent(getConfigurationView());
		configurationView.reload();
	}

	public void showUserManagementView() {
		btnAdvantageDefinition.setStyleName("top_button");
		btnConditionSelection.setStyleName("top_button");
		btnConfiguration.setStyleName("top_button");
		btnOverview.setStyleName("top_button");
		btnUsers.setStyleName("top_button_current");

		setMainComponent(getUserManagementView());
		usersManagementView.reload();
	}

	public void showLoginView() {
		PricingServiceApplication.removeUser(username);

		// Remove all data in session
		((WebApplicationContext) this.getApplication().getContext())
				.getHttpSession().invalidate();

		// Navigate to login view
		((PricingServiceApplication) getApplication())
				.setContent(new LoginView());
	}

	public void showActivePromotionListView(boolean reset) {
		showActivePromotionListView(reset, Boolean.FALSE);
	}
	
	public void showActivePromotionListView(boolean reset, boolean isResearch) {
		btnAdvantageDefinition.setStyleName("top_button");
		btnConditionSelection.setStyleName("top_button");
		btnConfiguration.setStyleName("top_button");
		btnOverview.setStyleName("top_button_current");
		btnUsers.setStyleName("top_button");

		setMainComponent(getActivePromotionListView());
		activeDomainRuleListView.setEnableReset(reset);
		
		if (isResearch) {
			activeDomainRuleListView.ReloadSearching();
		} else {
			activeDomainRuleListView.reload();
		}
	}

	public void showAdvantageDefinitionView() {

		btnAdvantageDefinition.setStyleName("top_button_current");
		btnConditionSelection.setStyleName("top_button");
		btnConfiguration.setStyleName("top_button");
		btnOverview.setStyleName("top_button");
		btnUsers.setStyleName("top_button");

		setMainComponent(getAdvantageDefinitionView());
	}

	public void showConditionSelectionView() {

		btnAdvantageDefinition.setStyleName("top_button");
		btnConditionSelection.setStyleName("top_button_current");
		btnConfiguration.setStyleName("top_button");
		btnOverview.setStyleName("top_button");
		btnUsers.setStyleName("top_button");

		setMainComponent(getConditionSelectionView());
	}

	private Component getUserManagementView() {
		if (usersManagementView == null) {
			usersManagementView = new UsersManagementView();
		}
		return usersManagementView;
	}

	private Component getAdvantageDefinitionView() {
		if (advantageView == null) {
			advantageView = new AdvantageView(this);
		}
		return advantageView;
	}

	private Component getConditionSelectionView() {
		if (conditionView == null) {
			conditionView = new ConditionView(this);
		}
		return conditionView;
	}

	private Component getConfigurationView() {
		if (configurationView == null) {
			configurationView = new ConfigurationView(this);
		}
		return configurationView;
	}

	public Component getActivePromotionListView() {
		if (activeDomainRuleListView == null) {
			activeDomainRuleListView = new ActiveDomainRuleListView(this);
		}
		return activeDomainRuleListView;
	}

	private void setMainComponent(Component c) {
		// add Main Component
		c.setWidth("1100px");
		mainViewLayout.removeComponent("content_containner");
		mainViewLayout.addComponent(c, "content_containner");
	}

	@Override
	public void setI18N(I18N i18n) {

	}

	@Override
	public void localeChanged(I18N sender, Locale oldLocale, Locale newLocale) {

	}
}
